import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Drawer, Space, Popconfirm, Switch, Tag, Layout } from 'antd';
import React, { useState, useRef } from 'react';
import { useAccess, Access } from 'umi';
import { useRequestHandle, getSorter } from '@/utils/utils';
import SaveForm from './components/SaveForm';
import { ProDescriptions } from '@ant-design/pro-components';
import ProMaxTable from '@/components/ProMaxTable';
import {
  treeDataQuery,
  query,
  update,
  add,
  get,
  statusChange
} from './service';
import operation from './operation';
import OrganizationTree from '@/components/OrganizationTree';
import styles from './index.less';

const { Sider, Content } = Layout

const Organization = () => {
  const [saveModalVisible, setSaveModalVisible] = useState(false);
  const [updateFormValues, setUpdateFormValues] = useState({});
  const actionRef = useRef();
  const orgActionRef = useRef();
  const [row, setRow] = useState();
  const { canOperation, canShowOption } = useAccess();
  // 是否显示操作列
  const isShowOptionColumn = canShowOption([operation.update, operation.delete]);
  // 刷新
  const reload = () => {
    if (actionRef.current) {
      actionRef.current.reload();
    }
    if (orgActionRef.current) {
      orgActionRef.current.reload();
    }
  };




  // 新增
  const addRequest = useRequestHandle(add, () => {
    message.success('创建成功.');
    setSaveModalVisible(false);
    reload();
  });

  // 更新
  const updateRequest = useRequestHandle(update, () => {
    message.success('更新成功.');
    setSaveModalVisible(false);
    setUpdateFormValues({});
    reload();
  });

  // 状态变更
  const statusChangeRequest = useRequestHandle(statusChange, () => {
    message.success('操作成功.');
    reload();
  });




  const columns = [

    {
      title: '名称',
      dataIndex: 'name',
      fixed: 'left',
      width: 170,
      ellipsis: true,
      render: (dom, entity) => <a onClick={() => setRow(entity)}>{dom}</a>,
    },
    {
      title: '上级部门',
      dataIndex: 'parentName',
      ellipsis: true,
      width: 170,
      hideInSearch: true
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      ellipsis: true,
      width: 170,
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      hideInSearch: true,
      width: 80,
      render: (_, record) => {
        const isChecked = record.status === 1;
        const canChangeStatus = canOperation(operation.statusChange);
        if (!canChangeStatus) {
          return isChecked ? <Tag color="#87d068">启用</Tag> : <Tag color="#f50">禁用</Tag>;
        }
        const title = isChecked ? '确定要禁用该数据吗？' : '确定要启用该数据吗？';
        return (
          <>
            <Popconfirm
              placement="top"
              title={title}
              onConfirm={(e) => {
                e.stopPropagation();
                statusChangeRequest.run({ id: record.id });
              }}
              okText="确定"
              cancelText="取消"
            >
              <Switch
                loading={statusChangeRequest.loading}
                checkedChildren="启用"
                unCheckedChildren="禁用"
                checked={isChecked}
              />
            </Popconfirm>
          </>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'created',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 75,
      hideInTable: !isShowOptionColumn,
      fixed: 'right',
      render: (_, record) => (
        <Space size={'small'}>
          <Access accessible={canOperation(operation.update)}>
            <Button
              type="primary"
              size="small"
              onClick={async () => {
                const result = await get({ id: record.id });
                if (!result.success) {
                  message.error(result.message);
                  return;
                }
                setSaveModalVisible(true);
                setUpdateFormValues(result.data);
              }}
            >
              编辑
            </Button>
          </Access>


        </Space>
      ),
    },
  ];
  const [organizationId, setOrganizationId] = useState(null);
  const [organizationName, setOrganizationName] = useState(null);

  return (
    <>
      <Layout>
        <Sider width={300} className={styles.orgTree} theme="light">

          <OrganizationTree
            ref={orgActionRef}
            req={treeDataQuery}
            params={{ parentId: "" }}
            chooseFirst
            onSelect={(row) => {
              setOrganizationId(row?.id ?? null);
              setOrganizationName(row?.name ?? null);
            }}
          />
        </Sider>
        <Content>
          <ProMaxTable
            headerTitle={
              <Space>
                <Access key="create" accessible={canOperation(operation.create)}>
                  <Button type="primary" onClick={() => setSaveModalVisible(true)}>
                    <PlusOutlined /> 创建
                  </Button>
                </Access>


              </Space>
            }
            actionRef={actionRef}
            rowKey="id"
            search={false}
            expandable={{
              defaultExpandAllRows: true,
            }}

            options={{
              search: {
                placeholder: '请输入关键字',
              },
              fullScreen: false,
            }}

            request={async (params, sorter, filter) => {
              if (params.parentId === null) {
                return [];
              }
              const data = params;
              data.pageIndex = params.current;
              const result = await query({ ...data, ...getSorter(sorter), filter });
              if (result.success) {
                return {
                  ...result,
                  total: result.data.totalItems,
                };
              }
              return [];
            }}
            postData={(data) => {
              return !data ? [] : data.items;
            }}
            params={{
              parentId: organizationId,
              type: 1
            }}

            columns={columns}
            rowSelection={false}
          />
        </Content>
      </Layout>
      <SaveForm
        onSubmit={async (value) => {
          const params = Object.assign(value, { status: value.status ? 1 : 0 });
          if (params.id) {
            updateRequest.run(params);
          } else {
            addRequest.run(params);
          }
        }}
        organizationId={organizationId}
        organizationName={organizationName}
        onCancel={() => {
          setSaveModalVisible(false);
          setUpdateFormValues({});
        }}
        loading={updateRequest.loading || addRequest.loading}
        modalVisible={saveModalVisible}
        record={updateFormValues}
      />


      <Drawer
        width={600}
        open={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.id && (
          <ProDescriptions
            column={2}
            title={row?.name}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.id,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </>
  );
};

export default Organization;